package top.likeqc.leetcode.editor.cn;

/**
 * @see <a href="https://leetcode.cn/problems/merge-in-between-linked-lists">leetcode题库</a>
 */
public class MergeInBetweenLinkedLists {
    public static void main(String[] args) {
        Solution solution = new MergeInBetweenLinkedLists().new Solution();
    }
    /**
     * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode()
     * {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
     * this.next = next; } }
     */
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {}

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    // leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
            ListNode list2Right = list2;
            while (list2Right.next != null) {
                list2Right = list2Right.next;
            }

            ListNode p = list1;
            ListNode list1aLeft = list1, list1bRight = list1;
            for (int i = 1; i <= b; i++) {
                if (i == a) {
                    list1aLeft = p;
                }
                if (i == b) {
                    list1bRight = p.next.next;
                }
                p = p.next;
            }

            list1aLeft.next = list2;
            list2Right.next = list1bRight;

            return list1;
        }
    }
    // leetcode submit region end(Prohibit modification and deletion)

}
